package com.edz.dudumifi.utils;

import com.alibaba.fastjson.JSONObject;
import com.edz.dudumifi.base.Config;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Map;

public class ClientSender {

    private static final String TAG = "ClientSender";

    private static ClientSender instance;

    private static BufferedReader in = null;
    private static PrintWriter out = null;

    private ClientSender() {
    }

    public static ClientSender getInstance() {
        synchronized (ClientSender.class) {
            if (instance == null) {
                instance = new ClientSender();
            }
            return instance;
        }
    }

    public static void send(String msg) throws IOException {
        Socket socket = new Socket(Config.gange_local_server_address, Config.gange_local_server_port);
        //向服务器发送消息
        out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), "utf-8"), true);
        out.println(msg);
        //接受来自服务器的消息
        in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8"));
        String str = in.readLine();
        if (!str.isEmpty()) {
            System.out.println("receive data:" + str);
            //map解析对象
            Map map = JSONObject.parseObject(str, Map.class);
            if (map != null) {
                String msgType = map.get("MsgType").toString();
                switch (msgType) {
                    case "WebRedirectConfig"://配置重定向界面
                        //{\"MsgType\":\"WebRedirectConfig\",\"Url\":\"https://res.v5fans.com/bigwifi/start.html?bid=2999\"}
                        System.out.println("重定向:" + str);
                        break;
                    case "SetNetRate": //限速
                        // {\"MsgType\":\"SetNetRate\",\"Rate\":\"400\"}
                        System.out.println("限速:" + str);
                        break;
                    case "OpenNetWork": //开网
                        //{\"MsgType\":\"OpenNetWork\",\"Url\":\"http://192.168.199.1/goform/CommConfig?cmd=CustInvoke&action=WebRedirectCtl&item=AcceptOneTemp&subitem=34:69:87:c0:e9:45_30\"}
                        System.out.println("放行上网:" + str);
                        break;
                    default:
                        break;
                }
            }
        }
        out.close();
        in.close();
        socket.close();
    }
}
